package com.example.demo.slice;

import com.example.demo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.ai.tts.TtsClient;
import ohos.ai.tts.TtsListener;
import ohos.ai.tts.TtsParams;
import ohos.ai.tts.constants.TtsEvent;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.PacMap;

import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class VoiceAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "MainAbilitySlice");
    private TextField infoText;
    private Button readBtn;
    private Text timeText;
    private boolean initItsResult;
    private static final int EVENT_MSG_INIT = 0x1000001;
    private static final int EVENT_MSG_TIME_COUNT = 0x1000002;
    private int time = 0;
    private Timer timer = null;
    private TimerTask timerTask = null;
    private Text mTvData;

    private EventHandler handler = new EventHandler(EventRunner.current()) {
        @Override
        protected void processEvent(InnerEvent event) {
            switch (event.eventId) {
                case EVENT_MSG_TIME_COUNT:
                    getUITaskDispatcher().delayDispatch(new Runnable() {
                        @Override
                        public void run() {
                            time = time + 1;
                            HiLog.info(LABEL_LOG, "播报耗时：" + Integer.toString(time) + " s");
                            timeText.setText("播报耗时：" + Integer.toString(time) + " s");
                        }
                    }, 0);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_voice);
        initView();
        initTtsEngine();
    }

    private void initView() {
        infoText = (TextField) findComponentById(ResourceTable.Id_text);
        readBtn = (Button) findComponentById(ResourceTable.Id_read_btn);
        timeText = (Text) findComponentById(ResourceTable.Id_time);
        readBtn.setClickedListener(this::readText);
        mTvData = (Text) findComponentById(ResourceTable.Id_tv_data);
    }

    private void initTtsEngine() {
        TtsClient.getInstance().create(this, ttsListener);
    }

    private void readText(Component component) {
        if (initItsResult) {
            HiLog.info(LABEL_LOG, "initItsResult is true, speakText");
            TtsClient.getInstance().speakText(infoText.getText(), null);
        } else {
            HiLog.error(LABEL_LOG, "initItsResult is false");
        }
    }

    private TtsListener ttsListener = new TtsListener() {
        @Override
        public void onEvent(int eventType, PacMap pacMap) {
            HiLog.info(LABEL_LOG, "onEvent...");
            // 定义TTS客户端创建成功的回调函数
            if (eventType == TtsEvent.CREATE_TTS_CLIENT_SUCCESS) {
                TtsParams ttsParams = new TtsParams();
                ttsParams.setDeviceId(UUID.randomUUID().toString());
                initItsResult = TtsClient.getInstance().init(ttsParams);
            }
        }

        @Override
        public void onStart(String utteranceId) {
            HiLog.info(LABEL_LOG, "onStart...");
        }

        @Override
        public void onProgress(String utteranceId, byte[] audioData, int progress) {
        }

        @Override
        public void onFinish(String utteranceId) {
            HiLog.info(LABEL_LOG, "onFinish...");
        }

        @Override
        public void onError(String s, String s1) {
            HiLog.info(LABEL_LOG, "onError...");
        }

        @Override
        public void onSpeechStart(String utteranceId) {
            // 开始计时
            HiLog.info(LABEL_LOG, "onSpeechStart...");
            if (timer == null && timerTask == null) {
                timer = new Timer();
                timerTask = new TimerTask() {
                    public void run() {
                        handler.sendEvent(EVENT_MSG_TIME_COUNT);
                    }
                };
                timer.schedule(timerTask, 0, 1000);
            }
        }

        @Override
        public void onSpeechProgressChanged(String utteranceId, int progress) {
        }

        @Override
        public void onSpeechFinish(String utteranceId) {
            // 结束计时
            HiLog.info(LABEL_LOG, "onSpeechFinish...");
            timer.cancel();
            time = 0;
            timer = null;
            timerTask = null;
        }
    };
}